// stores/useTranslationStore.ts
import { ElMessage } from 'element-plus'
import { defineStore } from 'pinia'
import { useConfigStore } from './configStore'
import md5 from 'crypto-js/md5'
import { translateApi } from '@renderer/api/translate'

export const useTranslationStore = defineStore('translation', {
  state: ()=>({
    text: "",
    translation: "",
    from: "auto",
    to: "zh",
    isTranslate: false,
    debounceTimer: null as ReturnType<typeof setTimeout> | null,
    loading: false,
    batchLoading: false,
  }),
  actions: {
    translateTextDebounced(text: string) {
      if (this.debounceTimer) {
        clearTimeout(this.debounceTimer)
        this.debounceTimer = null
      }
      this.debounceTimer = setTimeout(() => {
        this.translateText(text)
      }, 500)
    },

    async translateText(text: string) {
      const configStore = useConfigStore()
      const {
        baiduUrl = 'https://fanyi-api.baidu.com/api/trans/vip/translate',
        appid = '',
        appkey = '',
        salt = 'kiki',
      } = configStore.config

      // 检查必要配置
      if (!appid || !appkey) {
        ElMessage.error('请先配置百度翻译的 AppID 和 AppKey')
        return
      }

      try {
        this.loading = true
        // 1. 生成签名 (appid+q+salt+appkey 的MD5值)
        const signStr = appid + text + salt + appkey
        const sign = md5(signStr).toString()

        // 2. 构建请求参数
        const params = new URLSearchParams()
        params.append('q', text)
        params.append('from',this.from)
        params.append('to',this.to)
        params.append('appid', appid)
        params.append('salt', salt)
        params.append('sign', sign)

        // 3. 发送翻译请求
        const response = await fetch(baiduUrl, {
          method: 'POST',
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
          body: params
        })

        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`)

        const data = await response.json()

        // 4. 处理响应
        if (data.error_code) {
          throw new Error(`[${data.error_code}] ${data.error_msg}`)
        }

        // 5. 更新翻译结果
        this.text = text
        this.translation = data.trans_result
          ?.map((item: any) => item.dst)
          ?.join('\n') || ''
      } catch (error) {
        this.translation = "翻译错误"
      } finally{
        this.loading = false
      }
    },

    async translateTextFromTo(text: string,customeFrom:string,customeTo:string) {
      const configStore = useConfigStore()
      const {
        baiduUrl = 'https://fanyi-api.baidu.com/api/trans/vip/translate',
        appid = '',
        appkey = '',
        salt = 'kiki',
      } = configStore.config

      // 检查必要配置
      if (!appid || !appkey) {
        ElMessage.error('请先配置百度翻译的 AppID 和 AppKey')
        return
      }

      try {
        this.loading = true
        // 1. 生成签名 (appid+q+salt+appkey 的MD5值)
        const signStr = appid + text + salt + appkey
        const sign = md5(signStr).toString()

        // 2. 构建请求参数
        const params = new URLSearchParams()
        params.append('q', text)
        params.append('from',customeFrom)
        params.append('to',customeTo)
        params.append('appid', appid)
        params.append('salt', salt)
        params.append('sign', sign)

        // 3. 发送翻译请求
        const response = await fetch(baiduUrl, {
          method: 'POST',
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
          body: params
        })

        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`)

        const data = await response.json()

        // 4. 处理响应
        if (data.error_code) {
          throw new Error(`[${data.error_code}] ${data.error_msg}`)
        }

        return data.trans_result
          ?.map((item: any) => item.dst)
          ?.join('\n') || ''
      } catch (error) {
         return "翻译错误"
      } finally{
        this.loading = false
      }
    },

    async batchTranslateNotFoundTags(notFoundTags: string[]) {
      if (notFoundTags.length === 0) {
        ElMessage.info('没有需要翻译的标签')
        return []
      }

      const configStore = useConfigStore()
      const {
        baiduUrl = 'https://fanyi-api.baidu.com/api/trans/vip/translate',
        appid = '',
        appkey = '',
        salt = 'kiki',
      } = configStore.config

      if (!appid || !appkey) {
        ElMessage.error('请先配置百度翻译的 AppID 和 AppKey')
        return []
      }

      try {
        this.batchLoading = true // 开始批量翻译，按钮进入loading状态

        // 1. 构造批量翻译请求（百度API支持用换行分隔多个文本）
        const textToTranslate = notFoundTags.join('\n')
        const signStr = appid + textToTranslate + salt + appkey
        const sign = md5(signStr).toString()

        const params = new URLSearchParams()
        params.append('q', textToTranslate)
        params.append('from', this.from)
        params.append('to', this.to == 'en' ? 'zh':this.to)
        params.append('appid', appid)
        params.append('salt', salt)
        params.append('sign', sign)

        // 2. 发送批量翻译请求
        const response = await fetch(baiduUrl, {
          method: 'POST',
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
          body: params
        })

        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`)
        const data = await response.json()

        if (data.error_code) {
          throw new Error(`[${data.error_code}] ${data.error_msg}`)
        }
        // 3. 处理翻译结果（映射为 {en, cn} 格式的数组）
        const translatedResults = data.trans_result?.map((item: any, index: number) => ({
          en: notFoundTags[index], // 原始未翻译的标签（en）
          cn: item.dst, // 翻译结果（cn）
          hit_count: 1 // 初始命中计数
        })) || []

        // 4. 调用批量插入接口保存到本地库
        if (translatedResults.length > 0) {
          await translateApi().batchAddTranslate(translatedResults)
          ElMessage.success(`成功翻译并保存 ${translatedResults.length} 个标签`)
        }
        return translatedResults
      } catch (error) {
        const message = error instanceof Error ? error.message : '批量翻译失败'
        ElMessage.error(`批量翻译错误: ${message}`)
        return []
      } finally {
        this.batchLoading = false // 结束批量翻译，按钮恢复正常状态
      }
    }
  }
})
